//
//  DR_LanguageVC.swift
//  DocReaderRP
//
//  Created by  mac on 2025/11/13.
//

import UIKit
import GoogleMobileAds

class DR_LanguageVC: DR_BaseVC {

    private var languages: [(code: String, name: String)] = []
    private var selectedLanguageCode: String = ""
    private var languageViews: [UIView] = []
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // 刷新表格以确保选中状态正确显示
        loadAdmob()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // 获取可用语言列表
        languages = LanguageManager.shared.getAvailableLanguages()
        selectedLanguageCode = LanguageManager.shared.getCurrentLanguage()
        
        setupUI()
        setupConstraints()
    }
    
    private func loadAdmob(){
        // 先移除所有现有的原生广告视图
//        removeAllNativeAdViews()
//
//        RaeAnalytics.logEvent(.ad_scense, ["sceneName":"language_native"])
//        if let nativeAd = WT_AdManager.shared.checkAndGetNativeAd(for: .languageNative) {
//            print("✅ 获取到原生广告: \(nativeAd.headline ?? "无标题")")
//            // 这里可以创建原生广告视图并显示
//            RaeAnalytics.logEvent(.ad_show, ["sceneName":"language_native"])
//            showNativeAdDirectly(nativeAd: nativeAd)
//        } else {
//            print("❌ 场景 createNative 没有可用的原生广告")
//        }
        if let nativeAd = DR_NativeAdManager.shared.getNativeAd(for: "language_native") {
            removeAllNativeAdViews()
            showNativeAdDirectly(nativeAd: nativeAd)
        }
    }
    
    private func setupUI(){
        view.addSubview(backButton)
        view.addSubview(titleLabel)
        view.addSubview(scrollView)
        view.addSubview(doneButton)
        
        scrollView.addSubview(contentView)
        
        // 创建语言选项视图
        for (index, language) in languages.enumerated() {
            let languageView = createLanguageView(language: language, index: index)
            contentView.addSubview(languageView)
            languageViews.append(languageView)
        }
        
        backButton.addTarget(self, action: #selector(clickBackButton), for: .touchUpInside)
        doneButton.addTarget(self, action: #selector(clickDoneButton), for: .touchUpInside)
    }
    
    private func createLanguageView(language: (code: String, name: String), index: Int) -> UIView {
        let container = UIView()
        container.backgroundColor = UIColor(red: 0.95, green: 0.95, blue: 0.95, alpha: 1.0)
        container.layer.cornerRadius = 12
        container.layer.borderWidth = 0
        container.layer.borderColor = UIColor.clear.cgColor
        
        let label = UILabel()
        label.text = language.name
        label.font = UIFont.systemFont(ofSize: 16)
        label.textColor = .black
        
        let checkImageView = UIImageView()
        checkImageView.image = UIImage(named: "language_check")
        checkImageView.contentMode = .scaleAspectFit
        checkImageView.isHidden = language.code != selectedLanguageCode
        
        container.addSubview(label)
        container.addSubview(checkImageView)
        
        label.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(16)
            make.centerY.equalToSuperview()
        }
        
        checkImageView.snp.makeConstraints { make in
            make.trailing.equalToSuperview().offset(-16)
            make.centerY.equalToSuperview()
            make.width.height.equalTo(20)
        }
        
        // 设置选中状态
        if language.code == selectedLanguageCode {
            container.layer.borderWidth = 2
            container.layer.borderColor = "#333FFF".toColor.cgColor
        }
        
        // 添加点击手势
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(languageTapped(_:)))
        container.addGestureRecognizer(tapGesture)
        container.isUserInteractionEnabled = true
        container.tag = index
        
        return container
    }
    
    @objc private func languageTapped(_ gesture: UITapGestureRecognizer) {
        guard let view = gesture.view else { return }
        let index = view.tag
        
        if index < languages.count {
            // 更新选中状态
            selectedLanguageCode = languages[index].code
            updateLanguageViews()
        }
    }
    
    private func updateLanguageViews() {
        for (index, languageView) in languageViews.enumerated() {
            if index < languages.count {
                let language = languages[index]
                let isSelected = language.code == selectedLanguageCode
                
                // 更新边框
                if isSelected {
                    languageView.layer.borderWidth = 2
                    languageView.layer.borderColor = "#333FFF".toColor.cgColor
                } else {
                    languageView.layer.borderWidth = 0
                    languageView.layer.borderColor = UIColor.clear.cgColor
                }
                
                // 更新对勾图标
                if let checkImageView = languageView.subviews.first(where: { $0 is UIImageView }) as? UIImageView {
                    checkImageView.isHidden = !isSelected
                }
            }
        }
    }
    
    @objc private func clickBackButton(){
        self.navigationController?.popViewController(animated: true)
    }
    
    @objc private func clickDoneButton(){
        // 保存选中的语言
        let previousLanguage = LanguageManager.shared.getCurrentLanguage()
        LanguageManager.shared.setLanguage(selectedLanguageCode)
        
        // 如果语言发生变化，刷新整个app
        if previousLanguage != selectedLanguageCode {
            // 延迟一下，确保语言设置已保存
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
                    appDelegate.reloadApplication()
                }
            }
        } else {
            // 语言没有变化，直接返回上一页
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    private func setupConstraints(){
        backButton.snp.makeConstraints { make in
            make.leading.equalToSuperview()
            make.top.equalTo(view.safeAreaLayoutGuide)
            make.width.equalTo(56)
            make.height.equalTo(44)
        }
        
        titleLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalTo(backButton)
        }
        
        scrollView.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview()
            make.top.equalTo(backButton.snp.bottom).offset(20)
            make.bottom.equalTo(doneButton.snp.top).offset(-20)
        }
        
        contentView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            make.width.equalToSuperview()
        }
        
        // 语言选项布局
        for (index, languageView) in languageViews.enumerated() {
            languageView.snp.makeConstraints { make in
                make.leading.trailing.equalToSuperview().inset(20)
                make.height.equalTo(56)
                if index == 0 {
                    make.top.equalToSuperview().offset(0)
                } else {
                    make.top.equalTo(languageViews[index - 1].snp.bottom).offset(12)
                }
            }
        }
        
        // 设置contentView的底部约束
        if let lastView = languageViews.last {
            lastView.snp.makeConstraints { make in
                make.bottom.equalToSuperview().offset(-20)
            }
        }
        
        doneButton.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview().inset(20)
            make.bottom.equalTo(view.safeAreaLayoutGuide).offset(-20)
            make.height.equalTo(50)
        }
    }

    private let backButton: UIButton = {
        let v = UIButton(type: .custom)
        v.setImage("common_back".toImage, for: .normal)
        return v
    }()
    
    private let titleLabel: UILabel = {
        let v = UILabel()
        v.text = "setting_language".localized
        v.textColor = .black
        v.textAlignment = .center
        v.font = UIFont.boldSystemFont(ofSize: 18)
        return v
    }()
    
    private let scrollView: UIScrollView = {
        let scrollView = UIScrollView()
        scrollView.backgroundColor = .white
        scrollView.showsVerticalScrollIndicator = false
        return scrollView
    }()
    
    private let contentView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        return view
    }()
    
    private let doneButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setTitle("common_done".localized, for: .normal)
        button.setTitleColor(.white, for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .medium)
        button.backgroundColor = "#333FFF".toColor
        button.layer.cornerRadius = 25
        return button
    }()

}

// MARK: - AdNative
extension DR_LanguageVC {

    private func showNativeAdDirectly(nativeAd: NativeAd) {
        // 创建原生广告视图
        let adView = DR_NativeView()
        adView.adSense = "language_bottom"
        adView.nativeAd = nativeAd
        // 添加到界面
        view.addSubview(adView)
        adView.snp.makeConstraints { make in
            make.bottom.equalTo(view.safeAreaLayoutGuide)
            make.left.right.equalToSuperview()
            make.height.equalTo(308)
        }
    }
    
    // 移除所有原生广告视图
    private func removeAllNativeAdViews() {
        // 遍历所有子视图，移除 NativeView 类型的视图
        for subview in view.subviews {
            if subview is DR_NativeView {
                subview.removeFromSuperview()
            }
        }
    }
}
